package com.turing.post.antimoney.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.turing.post.antimoney.util.AlarmInfo;
import com.turing.post.antimoney.util.AlarmInfoDao;
import com.turing.post.antimoney.util.AlarmInfoDetail;
import com.turing.post.antimoney.util.AlarmInfoDetailDao;
import com.turing.post.antimoney.util.AlarmRule;
import com.turing.post.antimoney.util.AlarmRulesBusiness;
import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.Merchant;
import com.turing.post.organization.util.MerchantDao;
import com.turing.post.salesmanage.util.PersonalCustom;
import com.turing.post.salesmanage.util.PersonalCustomDao;
import com.turing.post.transaction.util.MchTradDetailDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

/**
 * 规则： 同一张卡，小额（小于100元）多次（五次以上）的刷卡
 */
@Remote
@Local
@Stateless(mappedName = "antimoney.impl.AlarmRule11")
public class AlarmRule11 implements AlarmRulesBusiness {

	@PersistenceContext
	protected EntityManager _em;
	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@EJB(mappedName = "transaction.impl.MchTradDetailDaoImpl")
	private MchTradDetailDao mchTradDetailDaoImpl;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;

	@EJB(mappedName = "salesmanage.impl.PersonalCustomDaoImpl")
	private PersonalCustomDao personalCustomDaoImpl;

	@EJB(mappedName = "antimoney.impl.AlarmInfoDaoImpl")
	private AlarmInfoDao alarmInfoDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantDaoImpl")
	private MerchantDao merchantDaoImpl;

	@EJB(mappedName = "antimoney.impl.AlarmInfoDetailDaoImpl")
	private AlarmInfoDetailDao alarmInfoDetailDaoImpl;

	@Override
	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public void runAlarmRules(String issueCompanyNo, Date tranDate,
			AlarmRule alarmRule) throws PCPSApplicationException {
		IssueCompany issueCompany = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(issueCompanyNo);
		String parameter[] = alarmRule.getRuleParameter().split(":");
		if (parameter.length > 0) {
			if (parameter.length < 2) {// 预警参数设置错误
				PCPSUtil.Log("渠道预警规则【" + alarmRule.getAlarmRuleDesc()
						+ "】的预警参数设置错误。");
				return;
			} else {
				// 预警参数设置不是数字
				if (!PCPSUtil.isNumeric(parameter[0])
						|| !PCPSUtil.isNumeric(parameter[1])) {
					PCPSUtil.Log("渠道预警规则【" + alarmRule.getAlarmRuleDesc()
							+ "】的预警参数设置错误，参数应该是数字。");
					return;
				} else {// 预警参数设置正常
					// 获取卡交易
					List<Object[]> objList = mchTradDetailDaoImpl
							.getCardDealSum(tranDate, new BigInteger(
									parameter[0].toString()));
					int times = Integer.parseInt(parameter[1]);
					for (Object[] obj : objList) {
						if (Integer.parseInt(obj[1].toString()) >= times) {
							// 获取购卡人信息
							ActivateCard card = activateCardDaoImpl
									.getActivateCardByCardNo(obj[0].toString());
							BigInteger customid = card.getOwnerId() == null ? card
									.getBuyerId()
									: card.getOwnerId();
							PersonalCustom custom = null;
							if (customid != null) {
								custom = personalCustomDaoImpl
										.getPersonalCustomByPersonalId(customid);
							}
							List<Object[]> detailList = mchTradDetailDaoImpl
									.getMchTradDetailByCardLastDeal(
											issueCompanyNo, obj[0].toString(),
											new BigInteger(parameter[0]
													.toString()), tranDate);
							if (detailList != null && detailList.size() > 0) {
								releaseAlarm(issueCompany, alarmRule, tranDate,
										custom, detailList);
							}
						}
					}
				}
			}
		} else {// 预警参数未设置
			PCPSUtil.Log("渠道预警规则【" + alarmRule.getAlarmRuleDesc()
					+ "】的预警参数未设置。");
			return;
		}
	}

	/**
	 * 发布风险信息
	 * 
	 * @param tranDate
	 * @param alarmRule
	 * @param issueCompany
	 * 
	 * @param alarmOrders存在风险的销售单
	 * @throws PCPSApplicationException
	 */
	private void releaseAlarm(IssueCompany issueCompany, AlarmRule alarmRule,
			Date tranDate, PersonalCustom custom, List<Object[]> detailList)
			throws PCPSApplicationException {
		AlarmInfo alarmInfo = new AlarmInfo();
		Merchant merchant = merchantDaoImpl.getMerchantByMerchantNo(detailList
				.get(0)[0].toString());
		alarmInfo.setAlarmRuleId(alarmRule.getAlarmRuleId());
		alarmInfo.setIssueCompanyNo(issueCompany.getIssueCompanyNo());
		alarmInfo.setBranchNo(merchant.getMerchantNo());
		alarmInfo.setBranchName(merchant.getMerchantName());
		alarmInfo.setAlarmTime(commonDaoImpl.getDatabaseSysTime());
		if (custom != null) {
			alarmInfo.setRiskCustomName(custom.getName());
		}
		alarmInfo.setAlarmReason(alarmRule.getAlarmRuleDesc());
		alarmInfo.setDealStatus("0");

		BigInteger alarmInfoId = alarmInfoDaoImpl.getMaxAlarmInfoId();
		alarmInfo.setAlarmInfoId(alarmInfoId);
		// 插入预警信息
		alarmInfoDaoImpl.insertAlarmInfo(alarmInfo);
		for (int j = 0; j < detailList.size(); j++) {
			Object[] obj = detailList.get(j);
			AlarmInfoDetail alarmInfoDetail = new AlarmInfoDetail();
			alarmInfoDetail.setAlarmInfoId(alarmInfoId);
			alarmInfoDetail.setSeqNo(j);
			alarmInfoDetail.setBusinessType("0");
			alarmInfoDetail.setMerchantNo(obj[0].toString());
			alarmInfoDetail.setTranSeqNo(obj[2].toString());
			alarmInfoDetail.setTranDate(tranDate);
			alarmInfoDetailDaoImpl.insertAlarmInfoDetail(alarmInfoDetail);
		}
	}
}
